package dapp

import (
	"context"
	"fmt"
	"gitee.com/go-mid/idgen/idgenservice"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"strconv"
	"time"
)

func GetNonce(ctx context.Context) (string, error) {
	res, err := idgenservice.DefaultIdgenService.GetId(ctx, &idgenservice.GetIdReq{
		Sname:     "common",
		Namespace: "default",
	})
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%d", res.Id), nil

}
func VarifyDappSignature(ctx context.Context, nonce, address, signature string) (bool, error) {
	nonceID, err := strconv.ParseInt(nonce, 10, 64)
	if err != nil {
		return false, status.Error(codes.Internal, err.Error())
	}
	res, err := idgenservice.DefaultIdgenService.GetTime(ctx, &idgenservice.GetTimeReq{
		Sname:     "common",
		Namespace: "default",
		Id:        nonceID,
	})
	if err != nil {
		return false, err
	}
	gap := time.Now().Unix() - res.TimestampMs/1000
	if gap < 0 {
		gap = -gap
	}
	//r如果nonce超过了10秒 则认为无效
	if gap > 10 {
		return false, status.Error(codes.Internal, "invalid nonce")
	}
	//	todo 校验signature
	return true, nil
}
